package com.example.myapplication.danmu

import android.animation.Animator
import android.animation.ObjectAnimator
import android.content.Context
import android.view.View
import android.view.animation.LinearInterpolator
import com.example.myapplication.shortvideo.utils.DisplayUtils

/**
 * @author: rongfeng
 * @date: 2022/3/11
 * @description
 */
class DanmuParts(context: Context) {
    val widthPixels = DisplayUtils.getWidthPixels().toFloat()
    var mDanmuPartsCallback: DanmuPartsCallback? = null
    var danmuView: PackageRewardDanmuView? = null
    var mObjectAnimator: ObjectAnimator? = null
    var isRun= false

    init {
        danmuView = PackageRewardDanmuView(context)

        val danmuWidth = DisplayUtils.measureView(danmuView as View).x.toFloat()
        mObjectAnimator = ObjectAnimator.ofFloat(danmuView as View, "translationX",
                widthPixels, -danmuWidth).setDuration(5000)
        mObjectAnimator?.let { translationX ->
            translationX.interpolator = LinearInterpolator()
            translationX.addListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) {
                    translationX.pause()
                    isRun = false
                    mDanmuPartsCallback?.onAnimationRepeat()
                }

                override fun onAnimationEnd(animation: Animator?) {
                }

                override fun onAnimationCancel(animation: Animator?) {
                }

                override fun onAnimationStart(animation: Animator?) {
                }
            })
            translationX.repeatCount = ObjectAnimator.INFINITE
        }
    }

    fun start() {
        mObjectAnimator?.let { translationX ->
            isRun = true
            val danmuWidth = DisplayUtils.measureView(danmuView as View).x.toFloat()

            translationX.setFloatValues(widthPixels, -danmuWidth)

            val duration = 5000 / widthPixels * (widthPixels + danmuWidth)

            val nextStartTime = danmuWidth / (widthPixels + danmuWidth) * duration

            translationX.duration = duration.toLong()

            translationX.removeAllUpdateListeners()
            translationX.addUpdateListener {
                if (it.currentPlayTime > nextStartTime) {
                    translationX.removeAllUpdateListeners()
                    mDanmuPartsCallback?.nextDanmu()
                }
            }
            translationX.start()
        }
    }

    fun setData(content: String) {
        danmuView?.setData(content)
    }


    fun isReusing(): Boolean {
        return mObjectAnimator?.isPaused ?: false
    }

    interface DanmuPartsCallback {
        fun nextDanmu()
        fun onAnimationRepeat()
    }
}